/**
 * 退货确认单维护
 * @author shixc
 * @date 2019/03/08
 */
define(function () {

    var date = new Date();
    var END;
    var START;
    if ((date.getMonth() + 1).length > 1) {
        if (date.getDate().length > 1) {
            END = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
        } else {
            END = date.getFullYear() + '-' + (date.getMonth() + 1) + '-0' + date.getDate();
        }
    } else {
        if (date.getDate().length > 1) {
            END = date.getFullYear() + '-0' + (date.getMonth() + 1) + '-' + date.getDate();
        } else {
            END = date.getFullYear() + '-0' + (date.getMonth() + 1) + '-0' + date.getDate();
        }
    }
    date.setMonth(date.getMonth() - 3);
    if ((date.getMonth() + 1).length > 1) {
        if (date.getDate().length > 1) {
            START = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
        } else {
            START = date.getFullYear() + '-' + (date.getMonth() + 1) + '-0' + date.getDate();
        }
    } else {
        if (date.getDate().length > 1) {
            START = date.getFullYear() + '-0' + (date.getMonth() + 1) + '-' + date.getDate();
        } else {
            START = date.getFullYear() + '-0' + (date.getMonth() + 1) + '-0' + date.getDate();
        }
    }
    var self,
        doc = document,
        app = win.app,
        layui = win.layui,
        element,
        table,
        table_gwda = {},
        cols = [[
            {field: 'ID', type: 'checkbox', title: '选择', fixed: 'left'}
            , {
                field: 'TI004',
                width: 120,
                title: '客户',
                fixed: 'left',
                sort: true,
                search: 'default',
                searchOpts: {icon: true}
            }
            , {field: 'TI021', width: 80, title: '客户全称'}
            , {field: 'TI036', width: 80, title: '税率'}
            , {
                field: 'TI003', width: 80, title: '销退日', search: 'default', id: 'test',
                searchOpts: {type: 'daterange', default: [START, END]}, sort: true
            }
            , {
                field: 'UDF12_J', width: 120, title: '确认状态',
                filterDatas: app.datas_('crm_gwai760_udf11'), search: 'default',
                searchOpts: {type: 'select'}
            }
            , {field: 'UDF11', width: 80, title: '确认人'}
            , {field: 'UDF07', width: 80, title: '确认日期'}
            , {field: 'TI039', width: 80, title: '付款条件编号'}
            , {field: 'TI034', width: 80, title: '单据日期'}
            , {
                field: 'UDF12_I', width: 80, title: '返利类型',
                filterDatas: app.datas_('crm_gwai710_gwcs117').concat({code: '', value: '全部'}), search: 'default',
                searchOpts: {type: 'select'}
            }
            , {field: 'TI002', width: 80, title: '单号', search: 'default'}
            , {field: 'TI020', width: 80, title: '备注'}
            , {field: 'TI008', width: 80, title: '币种'}
            , {field: 'TI009', width: 80, title: '汇率'}
            , {field: 'TJ003', width: 80, title: '序号'}
            , {field: 'TJ004', width: 80, title: '品号', search: 'default', searchOpts: {icon: true}}
            , {field: 'TJ005', width: 80, title: '品名'}
            , {field: 'TJ006', width: 80, title: '规格'}
            , {field: 'TJ007', width: 80, title: '数量'}
            , {field: 'TJ008', width: 80, title: '单位'}
            , {field: 'TJ012', width: 80, title: '金额'}
            , {field: 'TJ013', width: 80, title: '退货仓库'}
            , {field: 'TJ016', width: 80, title: '销货单号'}
            , {field: 'TJ017', width: 80, title: '销货序号'}
            , {field: 'TJ031', width: 80, title: '原币税前金额'}
            , {field: 'TJ032', width: 80, title: '原币税额'}
            , {field: 'TJ033', width: 80, title: '本币税前金额'}
            , {field: 'TJ034', width: 80, title: '本币税额'}
            , {field: 'TJ035', width: 80, title: '包装数量'}
            , {field: 'TJ036', width: 80, title: '包装单位'}
            , {field: 'TI029', width: 80, title: '总数量'}
            , {field: 'TI037', width: 80, title: '总金额'}
            , {field: 'TI040', width: 80, title: '总包装数量'}
            , {
                field: 'COMPANY', width: 80, title: '法人', hide: true
                , search: 'default', searchOpts: {icon: true}
            }
            // , {
            //     width: 60,
            //     title: '',
            //     toolbar: '#script-gwai760setting',
            //     fixed: 'right',
            //     align: 'center',
            //     unresize: true
            // }
        ]],
        gwai760SettingAction, gwai760table, company, laydate
    ;

    var Gwai760 = app.Module.extend({
        init: function () {
            self = this;
            self._super({
                _tag: 'gwai760',
                _searchs: [{
                    id: 'gwai760', tableId: 'gwai760_table', datas: cols[0]
                }],
                _loadTplsFull: [{
                    dom: 'common_open_window', tpl: 'common/_open_window'
                }, {
                    dom: 'common_open_copti', tpl: 'common/_open_copti'
                }]
            }, win);
        },

        initTable: function () {
            layui.use(['table', 'laydate'], function () {
                laydate = layui.laydate;
                laydate.render({
                    elem: '#test'
                    , range: true
                    , value: '2018-06-24 - 2018-06-24'
                    , max: 0
                });
                table = layui.table;
                gwai760table = table.render({
                    elem: app.getByid(doc, 'gwai760_table'),
                    url: g_ctxPath + 'crm/gwai760/getList',
                    // exportsUrl: g_ctxPath + 'crm/gwai760/exportsData',
                    // exportsName: '退货确认单数据',
                    // importsUrl: g_ctxPath + 'crm/gwai760/importsData',
                    // exportsMbUrl: g_ctxPath + 'files/退货确认单维护.xlsx',
                    title: '退货确认单信息表',
                    method: 'post',
                    id: 'gwai760_table',
                    toolbar: '#table-toolbar',
                    defaultToolbar: ['filter'], //, 'exports_import'
                    height: 'full',
                    cols: cols,
                    loading: true,
                    page: true,
                    where: table_gwda,
                    done: function (res, curr, count) {
                        var data = res.data;
                        var mergeIndex = 0;//定位需要添加合并属性的行数
                        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
                        var columsName = ['TI029', 'TI037', 'TI040'];//需要合并的列名称
                        var columsIndex = [31, 32, 33];//需要合并的列索引值
                        for (var k = 0; k < columsName.length; k++)//这里循环所有要合并的列
                        {
                            var trArr = $(".layui-table-body>.layui-table").find("tr");//所有行

                            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                                if (data[i]['TI002'] === data[i - 1]['TI002']) { //后一行的值与前一行的值做比较，相同就需要合并
                                    mark += 1;
                                    tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                                        $(this).attr("rowspan", mark);
                                    });
                                    tdCurArr.each(function () {//当前行隐藏
                                        $(this).css("display", "none");
                                    });
                                } else {
                                    mergeIndex = i;
                                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                                }
                            }
                            mergeIndex = 0;
                            mark = 1;
                        }
                    }
                });

                var tipsIndex = null;

                table.on('checkbox(gwai760_table)', function (obj) {
                    var $ = layui.$;
                    var list = gwai760table.getDatas();
                    if (obj.checked == true) {
                        list.forEach(function (v) {
                            if (v.TI002 == obj.data.TI002) {
                                v.LAY_CHECKED = true;
                                $('.layui-table tr[data-index=' + v.LAY_TABLE_INDEX + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                            }
                        });
                    } else {
                        list.forEach(function (v) {
                            if (v.TI002 == obj.data.TI002) {
                                v.LAY_CHECKED = true;
                                $('.layui-table tr[data-index=' + v.LAY_TABLE_INDEX + '] input[type="checkbox"]').next().removeClass('layui-form-checked');
                            }
                        });
                    }

                });

                //监听事件
                table.on('toolbar(gwai760_table)', function (obj) {
                    switch (obj.event) {
                        case 'return':
                            self.returns();
                            break;
                    }
                });

                $(doc).on('click', function () {
                    tipsIndex && layer.close(tipsIndex);
                });

            });
        },

        reloadTableCurr: function () {
            self._reloadTable({id: 'gwai760_table', where: table_gwda});
        },

        returns: function () {
            var checkStatus = table.checkStatus('gwai760_table');
            if (checkStatus.data.length > 0) {
                var _xdata = [];
                checkStatus.data.forEach(function (v) {
                    var _temp = app.fields_('gwai760');
                    if (v.UDF10 != 'Y') {
                        _temp.TI002 = v.TI002;
                        _temp.COMPANY = company;
                        _xdata.push(_temp);
                    }
                });
                app.ajax({
                    xurl: 'crm/gwai760/refund',
                    xdata: _xdata,
                    loading: true,
                    toJsonStr: true,
                    okmsg: '确认退货成功',
                    cb: function (result) {
                        if (result.ok) {
                            self.reloadTableCurr();
                        }
                    }
                });
            }
        },

        _ready: function () {
            this._super({
                vue: [{
                    el: '#page',
                    data: '',
                    searchId: 'gwai760',
                    methods: {
                        handleIconClick: function (field) {
                            var vue = this;
                            if (field == 'TJ004') {//产品开窗
                                self._openTplFull({
                                    tag: 'common_open_window',
                                    tagData: {
                                        config: {
                                            method: 'q_gwam001',
                                            columnList: [{label: '产品编号', prop: 'GWAM001', width: '150'},
                                                {label: '品名', prop: 'GWAML003', width: '150'},
                                                {label: '规格', prop: 'GWAML004', width: '150'}
                                            ]
                                        },
                                        cb: function (data) {
                                            vue.isearch.fields.TJ004 = data.GWAM001;
                                        }
                                    },
                                    index: 0,
                                    openOpts: {
                                        title: '选择产品',
                                        area: ['600px', '470px']
                                    }
                                });
                            } else if (field == 'TI004') {//客户开窗
                                self._openTplFull({
                                    tag:'common_open_window',
                                    tagData:{
                                        config:{
                                            method:'q_gwak001',
                                            columnList:[
                                                {label:'客户编号',prop:'GWAK001', width: 150},
                                                {label:'客户简称',prop:'GWAKL003', width: 150},
                                                {label:'客户全称',prop:'GWAKL004', width: 150}
                                            ]
                                        },
                                        cb: function (data) {
                                            vue.isearch.fields.TI004 = data.GWAK001;
                                        }
                                    },
                                    index: 0,
                                    openOpts: {
                                        title: '选择客户',
                                        area: ['600px', '470px']
                                    }
                                });
                            } else if (field == 'COMPANY') {//法人开窗
                                self._openTplFull({
                                    tag: 'common_open_window',
                                    tagData: {
                                        config: {
                                            method: 'q_gwde003',
                                            searchParam:{
                                                GWDE002 : "ERP账套"
                                            },
                                            columnList: [
                                                {label: '选项值', prop: 'GWDE003', width: '150'},
                                                {label: '选项名称', prop: 'GWDE004', width: '150'}
                                            ],
                                        },
                                        cb: function (data) {
                                            vue.isearch.fields.COMPANY = data.GWDE003;
                                            company = data.GWDE003;
                                        }
                                    },
                                    index: 0,
                                    openOpts: {
                                        title: '选择法人',
                                        area: ['600px', '470px']
                                    }
                                });
                            } else if (field == 'TI002') {//单号开窗
                                if (company == null || company == '') {
                                    app.showWarning("法人必选！");
                                    return;
                                } else {
                                    self._openTplFull({
                                        tag: 'common_open_copti',
                                        tagData: {
                                            company: company,
                                            cb: function (data) {
                                                vue.isearch.fields.TI002 = data.TI002;
                                            }
                                        },
                                        index: 1,
                                        openOpts: {
                                            title: '选择单号',
                                            area: ['600px', '430px']
                                        }
                                    });
                                }
                            }
                        }
                    },
                    watch: {
                        'isearch.fields.TI003': function (newValue, oldValue) {
                            if (newValue != null && newValue.length == 2) {
                                this.isearch.fields.TI003_START = newValue[0].replace(/-/g, '');
                                this.isearch.fields.TI003_END = newValue[1].replace(/-/g, '');
                                var oDate1 = newValue[0].split('-');
                                var oDate2 = newValue[1].split('-');
                                var strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
                                var strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
                                var iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24);
                                if (iDays > 100) {
                                    this.isearch.fields.TI003 = null;
                                    this.isearch.fields.TI003_START = '';
                                    this.isearch.fields.TI003_END = '';
                                    newValue = null;
                                    oldValue = null;
                                    app.showWarning('开始日期和结束日期的范围在100天内!');
                                }
                            } else {
                                this.isearch.fields.TI003_START = '';
                                this.isearch.fields.TI003_END = '';
                            }
                        },
                        'isearch.fields.COMPANY': function (val) {
                            if (val == '' || val == null) {
                                company = '';
                            }
                        },
                        'isearch.fields.UDF12_I': function (val) {
                            if (val == '1') {
                                this.isearch.fields.UDF12_I = '现款有返利';
                            } else if (val == '2') {
                                this.isearch.fields.UDF12_I = '现款无返利';
                            } else if (val == '3') {
                                this.isearch.fields.UDF12_I = '账期有返利';
                            } else if (val == '4') {
                                this.isearch.fields.UDF12_I = '账期无返利';
                            } else if (val == '5') {
                                this.isearch.fields.UDF12_I = '铺货有返利';
                            } else if (val == '6') {
                                this.isearch.fields.UDF12_I = '铺货无返利';
                            }
                        }
                    }
                }]
            });
            table_gwda.TI003_END = END.replace(/-/g, '');
            table_gwda.TI003_START = START.replace(/-/g, '');
            self.initTable();

            $('#itoSearch').click(function () {
                if (company == null || company == '') {
                    app.showWarning("法人必选！");
                    return;
                } else if (table_gwda.TI003_START == '' || table_gwda.TI003_START == null) {
                    app.showWarning("日期必选！");
                    return;
                }
            })
        },
        _lazy: function () {
            this._super();
            layui.use(['table'], function () {
                element = layui.element;
            });
        }
    });

    return new Gwai760();

});
